import { useState } from "react";
import { View } from "@tarojs/components";
import { useBoolean, useUpdateEffect } from "ahooks";
import Taro, { usePageScroll } from "@tarojs/taro";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import ByImage from "@/components/ui/ByImage";
import ByButton from "@/components/ui/ByButton";
import ByCounter from "@/components/ui/ByCounter";

import { MaterialDetailDTO } from "@/types/material";
import ApiMaterial from "@/api/material";
import useFetch from "@/hooks/useFetch";

type Props = {
  /**
   * 不可编辑数量
   */
  disabled?: boolean;
  shouActions?: boolean;
  source: MaterialDetailDTO;
  onChange?: (e: MaterialDetailDTO) => void;
  onClick?: () => void;
  onRemove?: () => void;
  onSwitch?: () => void;
  onReset?: (e: any) => void;
};

export default ({
  source,
  disabled,
  shouActions,
  onRemove,
  onClick,
  onChange,
  onReset,
}: Props) => {
  const [num, setNum] = useState(source.Num);
  useUpdateEffect(() => {
    if (num !== source.Num) setNum(source.Num);
  }, [source.Num]);

  const [flag, { setTrue, setFalse }] = useBoolean();
  usePageScroll(() => flag && setFalse());

  const toChange = () => {
    num !== source.Num && onChange?.({ ...source, Num: num });
  };

  // 临时的
  const onSwitch = () => Taro.navigateBack({ delta: 1 });

  const isReduce = source.IsReduce;
  const editable = !disabled && source.State === 0;

  const { run } = useFetch(ApiMaterial.cancel, "POST", {
    showLoading: true,
    manual: true,
    onSuccess(res) {
      onReset?.(res);
    },
  });
  // 重置
  const handleReset = (event) => {
    event.stopPropagation();
    run({
      chooseId: source.ChooseId,
      chooseMasterId: source.ChooseMasterId,
    });
  };

  return (
    <View className="border-t-1 border-[#eee]">
      <View className="my-2 bg-white p-2 rounded-md">
        <ByRow onClick={() => !disabled && onClick?.()}>
          <ByCol span="none" className="relative">
            <ByImage className="w-[160px] h-[160px] rounded-md mr-2" src="" />
            {isReduce && (
              <View className="absolute top-0 left-0 p-1 text-error bg-error-light text-xs rounded-tl-md rounded-br-md">
                已减配
              </View>
            )}
          </ByCol>

          <ByCol span={"auto"} className="flex flex-col">
            <ByText block>{source.MaterialName}</ByText>

            <ByText size="sm" type="third">
              {source.SourceBrandCategory}
              {source.MaterialSpec}
              {source.MaterialUnit}
            </ByText>

            <ByRow content="between" align="center">
              <View className="text-sm">¥ {source.MaterialPrice * num}</View>

              <View onClick={(e) => e.stopPropagation()}>
                {source.State === 0 ? (
                  <>
                    {flag ? (
                      <ByCounter
                        precision={2}
                        border={false}
                        value={source.Num}
                        onChange={setNum}
                        onBlur={toChange}
                      />
                    ) : (
                      <View
                        className="leading-[1] rounded-md bg-page px-2 p-1"
                        onClick={() => editable && setTrue()}
                      >
                        <ByText size="sm">{source.Num}</ByText>
                        <ByText size="sm">({source.MaterialUnit})</ByText>
                      </View>
                    )}
                  </>
                ) : (
                  <ByText size="xs" type="third">
                    未选材
                  </ByText>
                )}
              </View>
            </ByRow>

            {/* <ByText block className="my-1" size="sm" type="second">
          {source.Color && (
            <>
              <Text>颜色：{source.Color}</Text>
              <Text className="px-1">|</Text>
            </>
          )}
          {source.Standard && <Text>型材：{source.Color}</Text>}
        </ByText> */}

            <ByText size="sm" type="third">
              {source.Remark}
            </ByText>
          </ByCol>
        </ByRow>

        <ByRow className="mt-2 ">
          {shouActions && (
            <>
              <ByButton
                round
                inlineBlock
                size="small"
                type="error"
                variant="filled"
                className="flex-1 max-w-1/3 mx-1"
                onClick={onRemove}
              >
                {isReduce ? "取消" : ""}减配
              </ByButton>

              <ByButton
                round
                size="small"
                type="primary"
                variant="filled"
                className="flex-1 max-w-1/3 mx-1"
                onClick={onSwitch}
              >
                选材
              </ByButton>
            </>
          )}

          {source.State === 0 && (
            <ByButton
              round
              inlineBlock
              size="small"
              type="warning"
              variant="filled"
              className="flex-1 max-w-1/3 mx-1"
              onClick={handleReset}
            >
              重置
            </ByButton>
          )}
        </ByRow>
      </View>
    </View>
  );
};
